package com.echo.boot.structure.map;

import java.util.Comparator;
import java.util.LinkedList;
import java.util.Objects;

/**
 * Created with IntelliJ IDEA
 * Created By CQ
 * Date: 2020/6/7
 * Time: 12:48
 */
public class MyHashMap<K, V> implements Map<K, V> {
    private int size;
    private static final boolean RED = false;
    private static final boolean BLACK = true;
    private Comparator<K> comparator;
    private Node<K, V>[] table;
    private static final int DEFAULT_CAPACITY = 1 << 4;
    private static final float DEFAULT_LOAD_FACTOR = 0.75f;

    public MyHashMap() {
        table = new Node[DEFAULT_CAPACITY];
    }

    protected static class Node<K, V> {
        int hash;
        K key;
        V value;
        boolean color = RED;

        Node<K, V> left;
        Node<K, V> right;
        Node<K, V> parent;

        public Node(K key, V value, Node<K, V> parent) {
            int hash = key == null ? 0 : key.hashCode();
            this.hash = hash ^ (hash >>> 16);
            this.key = key;
            this.value = value;
            this.parent = parent;
        }


        public boolean isLeaf() {
            return left == null && right == null;
        }

        public boolean hasTwoChildren() {
            return left != null && right != null;
        }

        // 判断自己是不是左子树
        public boolean isLeftChild() {
            return parent != null && this == parent.left;
        }

        // 判断自己是不是右子树
        public boolean isRightChild() {
            return parent != null && this == parent.right;
        }

        // 返回父节点的兄弟节点

        public Node<K, V> sibling() {
            if (isLeftChild()) {
                return parent.right;
            }
            if (isRightChild()) {
                return parent.left;
            }
            return null;
        }

        @Override
        public String toString() {
            String parentString = null;
            String color = null;
            if (parent != null) {
                parentString = parent.key.toString();
            }
            if (this.color) {
                color = "black";
            } else {
                color = "red";
            }
            return key + "_p(" + parentString + ")_color(" + color + ")" + value;
        }

    }

    @Override
    public int size() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    @Override
    public void clear() {
        if (size == 0) {
            return;
        }
        int len = table.length;
        for (int i = 0; i < len; i++) {
            table[i] = null;
        }
    }

    @Override
    public V put(K key, V value) {
        resize();
        // 获得索引
        int index = index(key);
        Node<K, V> root = table[index];
        if (root == null) {
            root = new Node<>(key, value, null);
            table[index] = root;
            size++;
            fixAfterPut(root);
            return null;
        }
        // 添加到新的节点到红黑树

        Node<K, V> parent = root;
        Node<K, V> node = root;
        int cmp = 0;
        K k1 = key;
        int h1 = hash(key);
        Node<K, V> result = null;
        // 是否已经搜索过
        boolean searched = false;
        do {
            parent = node;
            K k2 = node.key;
            int h2 = node.hash;

            // 比较 hash 值,
            if (h1 > h2) {
                cmp = 1;
            } else if (h1 < h2) {
                cmp = -1;
                // 比较 equals
            } else if (Objects.equals(k1, k2)) {
                cmp = 0;
                // hash 值相等, 不 equals
                // 同一种类型是否具有和比较性
            } else if (k2 != null &&
                    k1 instanceof Comparable &&
                    k1.getClass() == k2.getClass() &&
                    (cmp = (((Comparable) k1).compareTo(k2))) != 0) {
                // 同一种类型,哈希值相等,但不equals,且不具备可比较性
                // 到这里 是 (同一种类型,不具备可比较性),只有全部扫描所有元素
                cmp = ((Comparable) k1).compareTo(k1);
            } else if (searched) {
                // 已经扫描
                cmp = System.identityHashCode(k1) - System.identityHashCode(k2);
            } else {
                if ((node.right != null && (result = node(node.right, k1)) != null) ||
                        (node.left != null && (result = node(node.left, k1)) != null)) {
                    node = result;
                    cmp = 0;
                } else {
                    // 还是没有找到 比较内存地址
                    searched = true;
                    cmp = System.identityHashCode(k1) - System.identityHashCode(k2);
                }
            }

            if (cmp < 0) {
                node = node.left;
            } else if (cmp > 0) {
                node = node.right;
            } else {
                // 相等的覆盖.
                V oldValue = node.value;
                node.key = key;
                node.value = value;
                node.hash = h1;
                return oldValue;
            }
        } while (node != null);
        Node<K, V> newNode = createNode(key, value, parent);
        if (cmp < 0) {
            parent.left = newNode;
        } else {
            parent.right = newNode;
        }
        size++;
        fixAfterPut(newNode);
        // 添加新节点 返回空
        return null;
    }

    @Override
    public V get(K key) {
        Node<K, V> node = node(key);
        return node != null ? node.value : null;
    }

    @Override
    public V remove(K key) {
        Node<K, V> root = table[index(key)];
        return remove(node(key));
    }

    private V remove(Node<K, V> node) {
        if (node == null) {
            return null;
        }
        Node<K, V> root = table[index(node)];
        Node<K, V> willNode = node;
        V oldValue = node.value;
        size--;
        // 度为2的节点
        if (node.hasTwoChildren()) {
            // 找到后继节点
//            Node<E> s = predecessor(node);
            Node<K, V> s = successor(node);
            // 用后继节点的值覆盖度为2的节点的值
            node.key = s.key;
            node.value = s.value;
            node.hash = s.hash;
            // 删除后继节点
            node = s;
        }
        // 删除node节点( node节点必然是 1 或者 0)
        // 删除node节点（node的度必然是1或者0）
        Node<K, V> replacement = node.left != null ? node.left : node.right;
        // node是度为1的节点
        if (replacement != null) {
            // 更改parent
            replacement.parent = node.parent;
            // 更改parent的left、right的指向
            if (node.parent == null) {
                // node是度为1的节点并且是根节点
                root = replacement;
            } else if (node == node.parent.left) {
                node.parent.left = replacement;
            } else {
                // node == node.parent.right
                node.parent.right = replacement;
            }
            // 删除节点后的调整
            fixAfterRemove(replacement);
        } else if (node.parent == null) {
            // node是叶子节点并且是根节点
            root = null;
            // 删除节点后的调整
//            afterRemove(node);
        } else {
            // node是叶子节点，但不是根节点
            if (node == node.parent.left) {
                node.parent.left = null;
            } else {
                node.parent.right = null;
            }
            // 删除节点后的调整
            fixAfterRemove(node);

        }
        afterRemove(willNode, node);
        return oldValue;
    }

    @Override
    public boolean containsKey(K key) {
        return node(key) != null;
    }

    @Override
    public boolean containsValue(V value) {
        if (size == 0) {
            return false;
        }
        LinkedList<Node<K, V>> queue = new LinkedList<>();
        for (int i = 0; i < table.length; i++) {
            if (table[i] == null) {
                continue;
            }
            queue.offer(table[i]);
            while (!queue.isEmpty()) {
                Node<K, V> node = queue.peek();
                if (valEquals(value, node.value)) {
                    return true;
                }
                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.left != null) {
                    queue.offer(node.right);
                }
            }
        }
        return false;
    }


    @Override
    public void traversal(MapVisitor<K, V> visitor) {
        if (visitor == null || size == 0) {
            return;
        }
        LinkedList<Node<K, V>> queue = new LinkedList<>();
        for (int i = 0; i < table.length; i++) {
            if (table[i] == null) {
                continue;
            }
            queue.offer(table[i]);
            while (!queue.isEmpty()) {
                Node<K, V> node = queue.peek();
                if (visitor.visit(node.key, node.value)) {
                    return;
                }
                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.left != null) {
                    queue.offer(node.right);
                }
            }
        }
    }


    private void fixAfterPut(Node<K, V> node) {
        Node<K, V> parent = node.parent;

        // 添加的是根节点,上溢到了根节点
        if (parent == null) {
            black(node);
            return;
        }
        // 父节点是黑色,直接返回
        if (isBlack(parent)) {
            return;
        }
        //uncle 节点判断
        Node<K, V> uncle = parent.sibling();
        // 祖父节点
        Node<K, V> grand = parent.parent;
        // 红黑树 与 4 阶 B 树等价
        // 如果uncle节点是红色,就出现上溢,出现上溢中间节点上移,分裂出2个子节点,最高的情况一直上溢到根节点
        // 保证红黑树属性,子节点必须为黑色(因为只有黑色才能独立一个子节点)
        // 向上移动的节点,当成一个新添加的节点,上移,再次重复此操作。
        // 上溢的情况(也就是添加的时候uncle 是红色的时候)
        if (isRed(uncle)) {
            black(parent);
            black(uncle);
            red(grand);
            fixAfterPut(grand);
            return;
        }
        // uncle 不是 红色
        // L
        if (parent.isLeftChild()) {
            if (node.isLeftChild()) {
                //LL
                black(parent);
                red(grand);
                rotateRight(grand);
            } else {
                //LR
                black(node);
                red(grand);
                rotateLeft(parent);
                rotateRight(grand);
            }
        } else {
            // R
            if (node.isLeftChild()) {
                // RL
                black(node);
                red(grand);
                rotateRight(parent);
                rotateLeft(grand);
            } else {
                // RR
                black(parent);
                red(grand);
                rotateLeft(grand);
            }
        }
    }

    private void rotateLeft(Node<K, V> grand) {
        Node<K, V> parent = grand.right;
        Node<K, V> child = parent.left;
        grand.right = child;
        parent.left = grand;
        afterRotate(grand, parent, child);

    }

    private void rotateRight(Node<K, V> grand) {
        Node<K, V> parent = grand.left;
        Node<K, V> child = parent.right;
        grand.left = child;
        parent.right = grand;
        afterRotate(grand, parent, child);
    }


    private void afterRotate(Node<K, V> grand, Node<K, V> parent, Node<K, V> child) {
        parent.parent = grand.parent;
        if (grand.isLeftChild()) {
            grand.parent.left = parent;
        } else if (grand.isRightChild()) {
            grand.parent.right = parent;
        } else {
            // grand是root节点
            table[index(grand)] = parent;
        }
        // 更新child的parent
        if (child != null) {
            child.parent = grand;
        }
        grand.parent = parent;
    }

    protected void fixAfterRemove(Node<K, V> node) {
        // 如果删除的节点是红色
        // 或者 用以取代删除节点的子节点是红色
        if (isRed(node)) {
            black(node);
            return;
        }

        Node<K, V> parent = node.parent;
        // 删除的是根节点
        if (parent == null) {
            return;
        }

        // 删除的是黑色叶子节点【下溢】
        // 判断被删除的node是左还是右
        boolean left = parent.left == null || node.isLeftChild();
        Node<K, V> sibling = left ? parent.right : parent.left;
        if (left) {
            // 被删除的节点在左边，兄弟节点在右边
            if (isRed(sibling)) {
                // 兄弟节点是红色
                black(sibling);
                red(parent);
                rotateLeft(parent);
                // 更换兄弟
                sibling = parent.right;
            }

            // 兄弟节点必然是黑色
            if (isBlack(sibling.left) && isBlack(sibling.right)) {
                // 兄弟节点没有1个红色子节点，父节点要向下跟兄弟节点合并
                boolean parentBlack = isBlack(parent);
                black(parent);
                red(sibling);
                if (parentBlack) {
                    fixAfterRemove(parent);
                }
            } else { // 兄弟节点至少有1个红色子节点，向兄弟节点借元素
                // 兄弟节点的左边是黑色，兄弟要先旋转
                if (isBlack(sibling.right)) {
                    rotateRight(sibling);
                    sibling = parent.right;
                }

                color(sibling, colorOf(parent));
                black(sibling.right);
                black(parent);
                rotateLeft(parent);
            }
        } else { // 被删除的节点在右边，兄弟节点在左边
            if (isRed(sibling)) { // 兄弟节点是红色
                black(sibling);
                red(parent);
                rotateRight(parent);
                // 更换兄弟
                sibling = parent.left;
            }

            // 兄弟节点必然是黑色
            if (isBlack(sibling.left) && isBlack(sibling.right)) {
                // 兄弟节点没有1个红色子节点，父节点要向下跟兄弟节点合并
                boolean parentBlack = isBlack(parent);
                black(parent);
                red(sibling);
                if (parentBlack) {
                    fixAfterRemove(parent);
                }
            } else { // 兄弟节点至少有1个红色子节点，向兄弟节点借元素
                // 兄弟节点的左边是黑色，兄弟要先旋转
                if (isBlack(sibling.left)) {
                    rotateLeft(sibling);
                    sibling = parent.left;
                }

                color(sibling, colorOf(parent));
                black(sibling.left);
                black(parent);
                rotateRight(parent);
            }
        }
    }

    protected void afterRemove(Node<K, V> wileNode, Node<K, V> removeNode) {

    }

    /*/*
     * @author CQ
     * @DESCRIPTION: 根据 key 算出对应的索引 (桶数组的位置)
     * @params: [key]
     * @return: int
     * @Date: 2020/6/12 9:52
     * @Modified By:
     */
    private int index(K key) {
        return hash(key) & (table.length - 1);
    }

    private int hash(K key) {
        if (key == null) {
            return 0;
        }
        int hash = key.hashCode();
        hash = hash ^ (hash >>> 16);
        return hash;
    }

    /*/*
     * @author CQ
     * @DESCRIPTION: 根据节点获取 索引 (桶数组的位置)
     * @params: [node]
     * @return: int
     * @Date: 2020/6/12 9:54
     * @Modified By:
     */
    private int index(Node<K, V> node) {
        return node.hash & (table.length - 1);
    }

    /*/*
     * @author CQ
     * @DESCRIPTION: 根据 key 找到 节点
     * @params: [key]
     * @return: MyHashMap.Node<K,V>
     * @Date: 2020/6/12 10:07
     * @Modified By:
     */
    private Node<K, V> node(K key) {
        Node<K, V> root = table[index(key)];
        return root == null ? null : node(root, key);
    }


    private Node<K, V> node(Node<K, V> node, K k1) {
        int h1 = hash(k1);
        int cmp = 0;
        Node<K, V> result = null;
        while (node != null) {
            K k2 = node.key;
            int h2 = node.hash;
            // 先比较 hash 值
            if (h1 > h2) {
                node = node.right;
            } else if (h1 < h2) {
                node = node.left;
                // 比较 equals
            } else if (Objects.equals(k1, k2)) {
                return node;
                // hash 相等, 不 equals;
                // 比较类名
            } else if (k2 != null &&
                    k1 instanceof Comparable &&
                    k1.getClass() == k2.getClass() &&
                    (cmp = (((Comparable) k1).compareTo(k2))) != 0) {
                // Compare 等于 0 ,不代表对象相等,只有走扫描.
                node = cmp > 0 ? node.right : node.left;
            } else if (node.right != null && (result = node(node.right, k1)) != null) {
                return result;
            } else {
                node = node.left;
            }
        }
        return null;
    }


    protected Node<K, V> createNode(K key, V value, Node<K, V> parent) {
        return new Node<>(key, value, parent);
    }

    private Node<K, V> color(Node<K, V> node, boolean color) {
        if (node == null) {
            return node;
        }
        node.color = color;
        return node;
    }

    private Node<K, V> red(Node<K, V> node) {
        return color(node, RED);
    }

    private Node<K, V> black(Node<K, V> node) {
        return color(node, BLACK);
    }

    private boolean colorOf(Node<K, V> node) {
        return node == null ? BLACK : node.color;
    }

    private boolean isRed(Node<K, V> node) {
        return colorOf(node) == RED;
    }

    private boolean isBlack(Node<K, V> node) {
        return colorOf(node) == BLACK;
    }


    /**
     * @author CQ
     * @DESCRIPTION: 返回前驱结点(中序遍历的前一个节点)
     * @params: []
     * @return: 前序节点
     * @Date: 2020/5/18 15:50
     * @Modified By:
     */
    protected Node<K, V> predecessor(Node<K, V> node) {
        if (node == null) {
            return null;
        }
        // 前驱节点在左子树中(left.right.right.right....)
        if (node.left != null) {
            // 左子树不为空,则找到它的最右节点
            Node<K, V> p = node.left;
            while (p.right != null) {
                p = p.right;
            }
            return p;
        }
        // 能来到这里说明左子树为空
        // 跳出循环条件
        // 当父节点不为空，则顺着父节点找，直到找到【某结点为父节点的右子节点】时
        while (node.parent != null && node.parent.left == node) {
            node = node.parent;
        }
        // 来到这里有以下两种情况：
        // node.parent == null	无前驱，说明是根结点
        // node.parent.right == node 找到【某结点为父节点的右子节点】
        return node.parent;
    }

    /**
     * @author CQ
     * @DESCRIPTION: 返回后驱结点(中序遍历的后一个节点)
     * @params: []
     * @return: 后序节点
     * @Date: 2020/5/18 15:50
     * @Modified By:
     */
    protected Node<K, V> successor(Node<K, V> node) {
        if (node == null) {
            return null;
        }
        if (node.right != null) {
            Node<K, V> p = node.right;
            while (p.left != null) {
                p = p.left;
            }
            return p;
        }
        // 来到这里说明没有右节点
        // 跳出循环条件
        // 当父节点不为空，则顺着父节点找，直到找到【某结点为父节点的左子节点】时
        while (node.parent != null && node.parent.right == node) {
            node = node.parent;
        }
        // 来到这里有以下两种情况：
        // node.parent == null   无后驱，说明是根结点
        // node.parent.left == node  找到【某结点为父节点的左子节点】
        return node.parent;

    }

    private boolean valEquals(V v1, V v2) {
        return Objects.equals(v1, v2);
//        return (v1 == v2) || (v1 != null && v1.equals(v2));
    }

    private void resize() {
        if ((size / table.length) <= DEFAULT_LOAD_FACTOR) {
            return;
        }
        Node<K, V>[] oldTable = table;
        table = new Node[table.length << 1];
        LinkedList<Node<K, V>> queue = new LinkedList<>();
        for (int i = 0; i < oldTable.length; i++) {
            if (oldTable[i] == null) {
                continue;
            }
            queue.offer(oldTable[i]);
            while (!queue.isEmpty()) {
                Node<K, V> node = queue.peek();

                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.left != null) {
                    queue.offer(node.right);
                }

                moveNode(node);
            }
        }

    }

    private void moveNode(Node<K, V> newNode) {
        // 重置
        newNode.parent = null;
        newNode.right = null;
        newNode.left = null;
        newNode.color = RED;

        // 获得索引
        int index = index(newNode);
        Node<K, V> root = table[index];
        if (root == null) {
            root = newNode;
            table[index] = root;
            fixAfterPut(root);
        }
        // 添加到新的节点到红黑树

        Node<K, V> parent = root;
        Node<K, V> node = root;
        int cmp = 0;
        K k1 = newNode.key;
        int h1 = newNode.hash;
        Node<K, V> result = null;
        // 是否已经搜索过
        boolean searched = false;
        do {
            parent = node;
            K k2 = node.key;
            int h2 = node.hash;

            // 比较 hash 值,
            if (h1 > h2) {
                cmp = 1;
            } else if (h1 < h2) {
                cmp = -1;
                // 比较 equals
            } else if (k2 != null &&
                    k1 instanceof Comparable &&
                    k1.getClass() == k2.getClass() &&
                    (cmp = (((Comparable) k1).compareTo(k2))) != 0) {
                // 同一种类型,哈希值相等,但不equals,且不具备可比较性
                // 到这里 是 (同一种类型,不具备可比较性),只有全部扫描所有元素
                cmp = ((Comparable) k1).compareTo(k1);
            } else {
                cmp = System.identityHashCode(k1) - System.identityHashCode(k2);
            }

            if (cmp < 0) {
                node = node.left;
            } else if (cmp > 0) {
                node = node.right;
            }
        } while (node != null);
        // 设置父节点
        node.parent = parent;
//        Node<K, V> newNode = createNode(key, value, parent);
        if (cmp < 0) {
            parent.left = newNode;
        } else {
            parent.right = newNode;
        }
        size++;
        fixAfterPut(newNode);
        // 添加新节点 返回空
    }

    //  打印
    @Override
    public Object root() {
//        return null;
        for (int i = 0; i < table.length; i++) {
            return table[i];
        }
        return null;
    }

    @Override
    public Object left(Object node) {
        return ((Node) node).left;
    }

    @Override
    public Object right(Object node) {
        return ((Node) node).right;
    }

    @Override
    public Object string(Object node) {
        return (Node) node;
    }
}
